<template>
  <div class="main">
    <div class="section">
      <div class="part">
        <div class="p-title">
          <div class="title">新消息通知</div>
          <div class="more">
            <router-link :to="{ path: '/publicity/message' }">
              更多<IconifyIconOnline
                icon="ep:arrow-right"
                width="14px"
                height="14px"
              />
            </router-link>
          </div>
        </div>
        <div
          class="p-cont"
          v-for="(item, index) in messageList"
          :key="index"
          @click="showMessageDetail(item)"
        >
          <div class="info">
            <div class="info-title">
              <span class="info-t-txt">{{ item.title }}</span>
              <span
                class="info-icon"
                v-if="!hasShowedMessageList.includes(item.type + '-' + item.id)"
                >NEW</span
              >
            </div>
            <!-- <div class="info-tip" v-html="item.description" /> -->
          </div>
          <div class="time">{{ item.createDate }}</div>
        </div>
      </div>
      <div class="part">
        <div class="p-title">
          <div class="title">最新宣传方案</div>
          <div class="more">
            <router-link :to="{ path: '/publicity/plan' }">
              更多<IconifyIconOnline
                icon="ep:arrow-right"
                width="14px"
                height="14px"
              />
            </router-link>
          </div>
        </div>
        <div
          class="p-cont"
          v-for="(item, index) in publicityList"
          :key="index"
          @click="showContentDetail(item)"
        >
          <div class="info">
            <div class="info-title">
              <span>{{ item.title }}</span>
              <!-- <span class="info-icon">NEW</span> -->
            </div>
            <!-- <div class="info-tip" v-html="item.description" /> -->
          </div>
          <div class="time">{{ item.createDate }}</div>
        </div>
      </div>
      <div class="part part-nopadding">
        <div class="self-info">
          <div class="face">
            <img :src="whlogoPng" alt="" srcset="" />
          </div>
          <div class="s-des">
            <div class="s-des-name">{{ userInfo.username }}</div>
            <div class="s-des-job">{{ userInfo.companyName }}</div>
          </div>
        </div>
        <div class="short-entry">
          <div class="title">快速入口</div>
          <div class="cont">
            <el-button @click="gotoPage('/supply/order')">
              <span>药品订单查询</span>
            </el-button>
            <!-- <el-button>
              <router-link to="/community/index">社区网点查询</router-link>
            </el-button> -->
            <el-button @click="gotoPage('/publicity/index')">
              <span>短信群发</span>
            </el-button>
            <el-button @click="gotoPage('/publicity/screen')">
              <span>数据大屏</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="panel">
      <div class="panel-title-cont">
        <div class="title">
          <span>健康城市达成率</span>
          <span class="time"
            >最后更新时间：{{ updateTimeString }} (每24小时更新一次)</span
          ><MyToolTip
            content="健康城市达标率：<br/>指标定义：万户健康从大健康的角度提出“健康教育、用药管理、大病保障”三大指标用以衡量健康城市的达成情况，分别对应医疗中的“治未病、治已病、保大病”，各个城市地区均可根据城市特点制定指标目标，系统将根据获取到的数据自动统计并显示各指标的达成情况。<br/>健康教育已参加：截止到当天，归属于所选区域的万户医学院App的用户数量。\n用药管理已参加：截止到当天，归属于所选区域并加入“用药管理计划”并正常享受该服务的用户数量<br/>大病保障已参加：截止到当天，归属于所选区域并正常享受万户健康大病保障服务的用户数<br/>"
          />
        </div>
        <myDestSelect ref="destSelectRef" @destChange="destChange" />
      </div>

      <div class="pie">
        <div class="p-item">
          <div class="p-title">健康教育</div>
          <div class="pie-cont">
            <div class="pie-chart" ref="healStudyRef" />
            <div class="pie-detail pink">
              <div class="info">
                <span class="label">目标:</span>
                <span>{{ formatNum(healthEducationStrObj.targetNum) }}人</span>
              </div>
              <div class="info">
                <span class="label">已参加:</span>
                <span
                  >{{
                    formatNum(healthEducationStrObj.participatedNum)
                  }}人</span
                >
              </div>
              <div class="info bold">达成率:</div>
              <div class="num">
                {{
                  convertToPrecentNum(
                    healthEducationStrObj.participatedNum,
                    healthEducationStrObj.targetNum
                  ) + "%"
                }}
              </div>
            </div>
          </div>
        </div>
        <div class="p-item">
          <div class="p-title">用药管理</div>
          <div class="pie-cont">
            <div class="pie-chart" ref="useDrugRef" />
            <div class="pie-detail yellow">
              <div class="info">
                <span class="label">目标:</span>
                <span>{{ formatNum(useDrugStrObj.targetNum) }}人</span>
              </div>
              <div class="info">
                <span class="label">已参加:</span>
                <span>{{ formatNum(useDrugStrObj.participatedNum) }}人</span>
              </div>
              <div class="info bold">达成率:</div>
              <div class="num">
                {{
                  convertToPrecentNum(
                    useDrugStrObj.participatedNum,
                    useDrugStrObj.targetNum
                  ) + "%"
                }}
              </div>
            </div>
          </div>
        </div>
        <div class="p-item">
          <div class="p-title">大病保障</div>
          <div class="pie-cont">
            <div class="pie-chart" ref="diseaseProtectRef" />
            <div class="pie-detail green-in">
              <div class="info">
                <span class="label">目标:</span>
                <span>{{ formatNum(diseaseProtectStrObj.targetNum) }}人</span>
              </div>
              <div class="info">
                <span class="label">已参加:</span>
                <span
                  >{{ formatNum(diseaseProtectStrObj.participatedNum) }}人</span
                >
              </div>
              <div class="info bold">达成率:</div>
              <div class="num">
                {{
                  convertToPrecentNum(
                    diseaseProtectStrObj.participatedNum,
                    diseaseProtectStrObj.targetNum
                  ) + "%"
                }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="panel">
      <div class="title">
        <span>当日数据看板</span>
        <span class="time"
          >最后更新时间：{{ updateTimeString }} (每60分钟更新一次)</span
        >
      </div>
      <div class="board">
        <div
          :class="['b-item', currentDayStaticType.includes(1) ? 'active' : '']"
          @click="changeCurDayStaticType(1)"
        >
          <div class="b-title">
            <span>订单成交（个）</span>
            <MyToolTip
              content="订单成交（个）\n指标定义：今日0点截至当前时间，已支付成功的订单数\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款订单"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.orderSaleCount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="18px"
                height="18px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="['b-item', currentDayStaticType.includes(2) ? 'active' : '']"
          @click="changeCurDayStaticType(2)"
        >
          <div class="b-title">
            <span>销售额 (元)</span>
            <MyToolTip
              content="销售额（元）\n指标定义：今日0点截至当前时间，所有成交订单的实收金额之和\n指标定义：今日0点截至当前时间，所有成交订单的实收金额之和"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.orderSaleAmount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="['b-item', currentDayStaticType.includes(3) ? 'active' : '']"
          @click="changeCurDayStaticType(3)"
        >
          <div class="b-title">
            <span>自费收款(元)</span>
            <MyToolTip
              content="自费收款（元）\n指标定义：今日0点截至当前时间，以微信、支付宝等在线支付的方式实收的金额之和\n统计范围：所有来自万户医学院App、公众号的订单；不剔除退款金额"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.selfSaleAmount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="[
            'b-item cursor-text',
            currentDayStaticType.includes(4) ? 'active' : ''
          ]"
          @click="showNoClickTip('4')"
        >
          <div class="b-title">
            <span>每年预期可节省医疗花费(元)</span>
            <MyToolTip
              content="每年预期可节省药品花费（元）\n指标定义：区域内通过PBM用药管理服务和中心式供药体系带来的降本增效，预期可为用户节省的药品花费，以及享受大病保障的用户出现后获得的保险赔付降低的医疗花费，两项花费的总和；"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.expectedSavingsDrugAmount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
          <div class="b-item-tip" v-if="curTip === '4'">此项不可点击</div>
        </div>
        <div
          :class="['b-item', currentDayStaticType.includes(5) ? 'active' : '']"
          @click="changeCurDayStaticType(5)"
        >
          <div class="b-title">
            <span>新增用药管理用户 (人)</span>
            <MyToolTip
              content="新增用药管理用户（人）\n指标定义：今日0点截止当前时间，首次加入“用药管理计划”服务的用户数量之和。\n统计范围：所有来自万户医学院App、公众号内的预约计划单，剔除曾经或正在使用的用户，确保用户首次使用。"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.newMedicationManagementCount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="['b-item', currentDayStaticType.includes(6) ? 'active' : '']"
          @click="changeCurDayStaticType(6)"
        >
          <div class="b-title">
            <span>新增预约服务（次）</span>
            <MyToolTip
              content="新增预约服务（次）\n指标定义：今日0点截止当前时间，新增的状态正常的用药管理计划单的数量。"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.newAdvanceOrderQuantity }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="['b-item', currentDayStaticType.includes(7) ? 'active' : '']"
          @click="changeCurDayStaticType(7)"
        >
          <div class="b-title">
            <span>新增大病保障（人）</span>
            <MyToolTip
              content="新增大病保障（人）\n指标定义：今日0点截止当前时间，新增的已承保的大病保单的数量。"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.newInsuranceCount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
        </div>
        <div
          :class="[
            'b-item cursor-text',
            currentDayStaticType.includes(8) ? 'active' : ''
          ]"
          @click="showNoClickTip('8')"
        >
          <div class="b-title">
            <span>每年预期可节省医保支出(元)</span>
            <MyToolTip
              content="每年预期可节省医保支出（元）\n指标定义：预期区域内享受健康管理服务用户的大病重疾发生率会降低，从而减少住院手术等医保支出。"
            />
          </div>
          <div class="b-num">
            {{ dayStatistics && dayStatistics.expectedSavingsInsuranceAmount }}
          </div>
          <div class="b-compare">
            <!-- <div class="b-c-item">
              较前一日<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />24%
            </div>
            <div class="b-c-item">
              较上周同期<IconifyIconOnline
                icon="charm:arrow-up"
                width="24px"
                height="24px"
                color="red"
              />25%
            </div> -->
          </div>
          <div class="b-item-tip" v-if="curTip === '8'">此项不可点击</div>
        </div>
      </div>
      <div class="line" ref="lineChartRef" />
    </div>
    <!-- 对话框，用户展示消息 -->

    <el-dialog v-model="msgDialogVisible" :title="curMessage.topTitle">
      <div class="dialog-detail">
        <div class="dialog-item">
          <div class="label">标题:</div>
          <div class="content">{{ curMessage.title }}</div>
        </div>
        <div class="dialog-item">
          <div class="label">描述:</div>
          <div class="content">
            <!-- <pre>{{ curMessage.description.trim() }}</pre> -->
            <div v-html="curMessage.description" />
          </div>
        </div>
        <div
          class="dialog-item"
          v-if="curMessage.files && curMessage.files.length"
        >
          <div class="label">附件:</div>
          <div class="content">
            <div
              class="con-item"
              v-for="(file, index) in curMessage.files"
              :key="index"
            >
              <span>
                {{ file.title }}
              </span>
              <a
                v-if="file.url"
                class="down-href"
                :href="file.url"
                download=""
                target="_blank"
                style="color: rgb(64, 158, 255); cursor: pointer"
                >下载</a
              >
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-tooltip
      v-model:visible="tipVisible"
      content="此项不可点击"
      placement="bottom"
      effect="dark"
      trigger="click"
      virtual-triggering
      :virtual-ref="tipTriggerRef"
    />
  </div>
</template>

<script setup lang="ts">
import {
  onBeforeMount,
  onMounted,
  Ref,
  onUnmounted,
  toRaw,
  markRaw
} from "vue";
import { useECharts } from "@pureadmin/utils";
import { ref } from "vue";
import * as echartsTypes from "echarts/types/dist/echarts";
import MyToolTip from "@/components/myToolTip.vue";
// 获取用户信息
import { useUserStoreHook } from "@/store/modules/user";
import { formatNum, convertToPrecentNum } from "@/utils/tools";
import { type publicityListType, type healthStatisticsType } from "@/api/types";
// 城市健康数据
import {
  getCityHealthStatistics,
  getPublicityGrogrammes,
  getMessageList,
  getDayStatistics,
  getDayStatisticsDetail
} from "@/api/index";

import { getContentManagementDetail } from "@/api/system";
// 地区选择控件
import myDestSelect, { destSelectType } from "@/components/myDestSelect.vue";
import { formatDate } from "../../utils/tools";
import whlogoPng from "@/assets/login/whlogo.png";
import { useRouter } from "vue-router";

const router = useRouter();

const localMessageStatusKey = "hasShowedMessageList";
const hasShowedMessageList = ref([]);

const msgDialogVisible = ref(false);
const curMessage = ref({
  topTitle: "",
  title: "",
  description: "",
  files: []
});
const tipVisible = ref(false);
const tipTriggerRef = ref(null);
const destSelectRef = ref<destSelectType | null>(null);

const curTip = ref("");

let tipTimeHandler = null;

function showNoClickTip(name) {
  curTip.value = name;
  if (tipTimeHandler) {
    clearTimeout(tipTimeHandler);
  }
  tipTimeHandler = setTimeout(() => {
    curTip.value = "";
  }, 3000);
}

// 获取日常数据
const dayStatistics = ref();

const currentDayStaticType = ref<Array<1 | 2 | 3 | 4 | 5 | 6 | 7 | 8>>([1]);

const unitObj = {
  1: "个",
  2: "元",
  3: "元",
  4: "元",
  5: "人",
  6: "次",
  7: "人",
  8: "元"
};

function gotoPage(url) {
  router.push({ path: url });
}

function changeCurDayStaticType(val) {
  const currentDayStaticTypeList = [val];
  // const currentDayStaticTypeList = currentDayStaticType.value;
  // const index = currentDayStaticTypeList.indexOf(val);
  // if (index > -1) {
  //   if (currentDayStaticTypeList.length === 1) {
  //     return;
  //   }
  //   currentDayStaticTypeList.splice(index, 1);
  // } else {
  //   currentDayStaticTypeList.push(val);
  // }
  currentDayStaticType.value = currentDayStaticTypeList;
  setLineChartOption(val);
}

const userStore = useUserStoreHook();

const userInfo = ref(userStore.userInfo);

const userRegions = userStore.userRegions;

// 宣传方案
const publicityList = ref<publicityListType>();
const messageList = ref<publicityListType>();
// 健康城市达成率
const healthStatistics = ref<healthStatisticsType>();

const healthEducationStrObj = ref({
  targetNum: 1,
  participatedNum: 0
});
const useDrugStrObj = ref({
  targetNum: 1,
  participatedNum: 0
});
const diseaseProtectStrObj = ref({
  targetNum: 1,
  participatedNum: 0
});

async function showContentDetail(item) {
  msgDialogVisible.value = true;
  const detail = await getContentManagementDetail(item.id);
  curMessage.value = detail;
  curMessage.value.topTitle = "宣传方案详情";
}

function saveMessageStatus(item) {
  hasShowedMessageList.value.push(item.type + "-" + item.id);

  localStorage.setItem(
    localMessageStatusKey,
    JSON.stringify(hasShowedMessageList.value)
  );
}

async function showMessageDetail(item) {
  msgDialogVisible.value = true;
  const detail = await getContentManagementDetail(item.id);
  curMessage.value = detail;
  curMessage.value.topTitle = "新消息详情";
  saveMessageStatus(item);
}

// 3个饼图
const healStudyRef = ref<HTMLDivElement | null>(null);
const useDrugRef = ref<HTMLDivElement | null>(null);
const diseaseProtectRef = ref<HTMLDivElement | null>(null);
let healStudyEchartIns = null;
let useDrugEchartIns = null;
let diseaseProtectEchartIns = null;

const gaugeHealStudyChartOptions = {
  grid: {
    left: "5",
    top: "5",
    right: "5",
    bottom: "5"
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  series: [
    {
      type: "gauge",
      startAngle: 90,
      endAngle: -270,
      radius: "100%",
      pointer: {
        show: false
      },
      progress: {
        show: true,
        overlap: false,
        roundCap: true,
        clip: false,
        itemStyle: {
          borderWidth: 1,
          borderColor: "#ff0",
          color: "#f00"
        }
      },
      axisLine: {
        lineStyle: {
          width: 10,
          color: [[1, "#0ff"]]
        }
      },
      splitLine: {
        show: false,
        distance: 0,
        length: 10
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        show: false,
        distance: 50
      },
      data: [
        {
          value: 0,
          title: {
            offsetCenter: ["0%", "-30%"],
            show: false
          },
          detail: {
            show: false,
            offsetCenter: ["0%", "-20%"]
          }
        }
      ],
      title: {
        fontSize: 14
      },
      detail: {
        width: 10,
        height: 14,
        fontSize: 14,
        color: "auto",
        borderColor: "auto",
        borderRadius: 20,
        borderWidth: 1,
        formatter: "{value}%"
      }
    }
  ]
};
const gaugeUseDrugChartOptions = {
  grid: {
    left: "5",
    top: "5",
    right: "5",
    bottom: "5"
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  series: [
    {
      type: "gauge",
      startAngle: 90,
      endAngle: -270,
      radius: "100%",
      pointer: {
        show: false
      },
      progress: {
        show: true,
        overlap: false,
        roundCap: true,
        clip: false,
        itemStyle: {
          borderWidth: 1,
          borderColor: "#ff0",
          color: "#f00"
        }
      },
      axisLine: {
        lineStyle: {
          width: 10,
          color: [[1, "#0ff"]]
        }
      },
      splitLine: {
        show: false,
        distance: 0,
        length: 10
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        show: false,
        distance: 50
      },
      data: [
        {
          value: 0,
          title: {
            offsetCenter: ["0%", "-30%"],
            show: false
          },
          detail: {
            show: false,
            offsetCenter: ["0%", "-20%"]
          }
        }
      ],
      title: {
        fontSize: 14
      },
      detail: {
        width: 10,
        height: 14,
        fontSize: 14,
        color: "auto",
        borderColor: "auto",
        borderRadius: 20,
        borderWidth: 1,
        formatter: "{value}%"
      }
    }
  ]
};
const gaugeDiseaseProtectChartOptions = {
  grid: {
    left: "5",
    top: "5",
    right: "5",
    bottom: "5"
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  series: [
    {
      type: "gauge",
      startAngle: 90,
      endAngle: -270,
      radius: "100%",
      pointer: {
        show: false
      },
      progress: {
        show: true,
        overlap: false,
        roundCap: true,
        clip: false,
        itemStyle: {
          borderWidth: 1,
          borderColor: "#ff0",
          color: "#f00"
        }
      },
      axisLine: {
        lineStyle: {
          width: 10,
          color: [[1, "#0ff"]]
        }
      },
      splitLine: {
        show: false,
        distance: 0,
        length: 10
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        show: false,
        distance: 50
      },
      data: [
        {
          value: 0,
          title: {
            offsetCenter: ["0%", "-30%"],
            show: false
          },
          detail: {
            show: false,
            offsetCenter: ["0%", "-20%"]
          }
        }
      ],
      title: {
        fontSize: 14
      },
      detail: {
        width: 10,
        height: 14,
        fontSize: 14,
        color: "auto",
        borderColor: "auto",
        borderRadius: 20,
        borderWidth: 1,
        formatter: "{value}%"
      }
    }
  ]
};
function initHealStudyGaugeChart(
  elRef: Ref<HTMLDivElement>,
  axisColor: string,
  lineColor: string,
  value?: number
): echartsTypes.ECharts {
  const { setOptions, getInstance } = markRaw(
    useECharts(elRef as Ref<HTMLDivElement>)
  );
  // const tempOptions = deepCopy<typeof gaugeChartOptions>(gaugeChartOptions);
  gaugeHealStudyChartOptions.series[0].progress.itemStyle.borderColor =
    lineColor;
  gaugeHealStudyChartOptions.series[0].progress.itemStyle.color = lineColor;
  gaugeHealStudyChartOptions.series[0].axisLine.lineStyle.color = [
    [1, axisColor]
  ];
  if (value) {
    gaugeHealStudyChartOptions.series[0].data[0].value = value;
  }

  // console.log("tempOptions:", JSON.stringify(tempOptions));
  setOptions(gaugeHealStudyChartOptions as any);

  return getInstance();
}
function initUseDrugGaugeChart(
  elRef: Ref<HTMLDivElement>,
  axisColor: string,
  lineColor: string,
  value?: number
): echartsTypes.ECharts {
  const { setOptions, getInstance } = markRaw(
    useECharts(elRef as Ref<HTMLDivElement>)
  );
  // const tempOptions = deepCopy<typeof gaugeChartOptions>(gaugeChartOptions);
  gaugeUseDrugChartOptions.series[0].progress.itemStyle.borderColor = lineColor;
  gaugeUseDrugChartOptions.series[0].progress.itemStyle.color = lineColor;
  gaugeUseDrugChartOptions.series[0].axisLine.lineStyle.color = [
    [1, axisColor]
  ];
  if (value) {
    gaugeUseDrugChartOptions.series[0].data[0].value = value;
  }
  // console.log("tempOptions:", JSON.stringify(gaugeUseDrugChartOptions));
  setOptions(toRaw(gaugeUseDrugChartOptions) as any);

  return getInstance();
}
function initDiseaseProtectGaugeChart(
  elRef: Ref<HTMLDivElement>,
  axisColor: string,
  lineColor: string,
  value?: number
): echartsTypes.ECharts {
  const { setOptions, getInstance } = markRaw(
    useECharts(elRef as Ref<HTMLDivElement>)
  );
  // const tempOptions = deepCopy<typeof gaugeChartOptions>(gaugeChartOptions);
  gaugeDiseaseProtectChartOptions.series[0].progress.itemStyle.borderColor =
    lineColor;
  gaugeDiseaseProtectChartOptions.series[0].progress.itemStyle.color =
    lineColor;
  gaugeDiseaseProtectChartOptions.series[0].axisLine.lineStyle.color = [
    [1, axisColor]
  ];
  if (value) {
    gaugeDiseaseProtectChartOptions.series[0].data[0].value = value;
  }
  // console.log("tempOptions:", JSON.stringify(tempOptions));
  setOptions(toRaw(gaugeDiseaseProtectChartOptions) as any);

  return getInstance();
}

function setHealStudyData(value) {
  // console.log("setHealStudyData value:", value);
  gaugeHealStudyChartOptions.series[0].data[0].value = value;

  healStudyEchartIns.setOption(gaugeHealStudyChartOptions as any);
}

function setUseDrugData(value) {
  // console.log("setUseDrugData value:", value);
  gaugeUseDrugChartOptions.series[0].data[0].value = value;

  useDrugEchartIns.setOption(gaugeUseDrugChartOptions);
}

function setDiseaseProtectData(value) {
  // console.log("setDiseaseProtectData value:", value);
  // gaugeChartOptions.series[0].data[0].value = value;
  gaugeDiseaseProtectChartOptions.series[0].data[0].value = value;
  diseaseProtectEchartIns.setOption(gaugeDiseaseProtectChartOptions);
}

const lineChartRef = ref<HTMLDivElement | null>(null);
let lineEchartsIns = null;

// const echarts = $echarts;
const lineChartOptions = {
  tooltip: {
    show: true,
    trigger: "axis"
  },
  title: {
    text: "趋势分析(人)",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "0%",
    top: "20%",
    right: "0%",
    bottom: "10%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    data: []
  },
  legend: {
    show: true,
    bottom: 20
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [0, 0, 0],
      type: "line"
    }
  ]
};

const updateTimeString = ref("");
function setUpdateStr() {
  const now = new Date();
  updateTimeString.value =
    formatDate(now) + ` ${now.getHours()}:${now.getMinutes()}`;
}

const statisticsDetailData = ref();

// 只需要加载页面的时候获取一次就可以了
async function getCurDayStaticData() {
  statisticsDetailData.value = await getDayStatisticsDetail(
    formatDate(new Date()),
    userRegions.isNationwide,
    destSelectRef.value.userSelectedRegions.provinceId,
    destSelectRef.value.userSelectedRegions.cityId,
    destSelectRef.value.userSelectedRegions.areaId
  );
  setLineChartOption(1);
  // 每年预期可节省医保支出和每年预期可节省医疗花费两个不存在折线图，所以默认赋值为00
  // let listLen = statisticsData['hours'].lenth
}

function initLineChart() {
  const { setOptions, getInstance } = markRaw(
    useECharts(lineChartRef as Ref<HTMLDivElement>)
  );
  setOptions(lineChartOptions as any);
  lineEchartsIns = getInstance();
}

function setLineChartOption(val) {
  // console.log("lineChartOptions:", lineChartOptions);
  lineChartOptions.title.text = `趋势分析(${unitObj[val]})`;
  lineChartOptions.xAxis.data = statisticsDetailData.value.hours;
  // 6个图标
  const keyNames = {
    1: {
      key: "orderSaleCount",
      name: "订单成交"
    },
    2: {
      key: "orderSaleAmount",
      name: "销售额"
    },
    3: {
      key: "selfSaleAmount",
      name: "自费收款"
    },
    4: {
      key: "expectedSavingsDrugAmount",
      name: "每年预期可节省药品花费"
    },
    5: {
      key: "newMedicationManagementCount",
      name: "新增用药管理用户"
    },
    6: {
      key: "newAdvanceOrderQuantity",
      name: "新增预约服务"
    },
    7: {
      key: "newInsuranceCount",
      name: "新增大病保障"
    },
    8: {
      key: "expectedSavingsInsuranceAmount",
      name: "每年预期可节省医保支出"
    }
  };
  // console.log("currentDayStaticType:", currentDayStaticType.value);
  const filterKeyNames = currentDayStaticType.value.map(item => {
    return keyNames[item];
  });
  if (lineChartOptions) {
    lineChartOptions.series = filterKeyNames.map(item => {
      return {
        name: item.name,
        data: statisticsDetailData.value[item.key],
        type: "line"
      };
    });
  }
  // console.log("lineChartOptions:", lineChartOptions);
  lineEchartsIns.clear();
  lineEchartsIns.setOption(lineChartOptions);
}

function initChart() {
  healStudyEchartIns = initHealStudyGaugeChart(
    healStudyRef,
    "#fff6f6",
    "#F66175"
  );
  useDrugEchartIns = initUseDrugGaugeChart(useDrugRef, "#EBF6F6", "#46CDCE");
  diseaseProtectEchartIns = initDiseaseProtectGaugeChart(
    diseaseProtectRef,
    "#EFF5FF",
    "#4892F9"
  );
  initLineChart();
}

function resizeChart() {
  // console.log("resizeChart");
  lineEchartsIns?.resize();
  healStudyEchartIns?.resize();
  useDrugEchartIns?.resize();
  diseaseProtectEchartIns?.resize();
}

function setEchart() {
  // healStudyEchartIns.value = initHealStudyGaugeChart(
  //   healStudyRef,
  //   "#fff6f6",
  //   "#F66175",
  //   convertToPrecentNum(
  //     healthEducationStrObj.value.participatedNum,
  //     healthEducationStrObj.value.targetNum
  //   )
  // );
  // useDrugEchartIns.value = initUseDrugGaugeChart(
  //   useDrugRef,
  //   "#EBF6F6",
  //   "#46CDCE",
  //   convertToPrecentNum(
  //     useDrugStrObj.value.participatedNum,
  //     useDrugStrObj.value.targetNum
  //   )
  // );
  // diseaseProtectEchartIns.value = initDiseaseProtectGaugeChart(
  //   diseaseProtectRef,
  //   "#EFF5FF",
  //   "#4892F9",
  //   convertToPrecentNum(
  //     diseaseProtectStrObj.value.participatedNum,
  //     diseaseProtectStrObj.value.targetNum
  //   )
  // );

  setHealStudyData(
    convertToPrecentNum(
      healthEducationStrObj.value.participatedNum,
      healthEducationStrObj.value.targetNum
    )
  );
  setUseDrugData(
    convertToPrecentNum(
      useDrugStrObj.value.participatedNum,
      useDrugStrObj.value.targetNum
    )
  );
  setDiseaseProtectData(
    convertToPrecentNum(
      diseaseProtectStrObj.value.participatedNum,
      diseaseProtectStrObj.value.targetNum
    )
  );
}

function destChange() {
  initDataAndChart();
}

async function initDataAndChart() {
  publicityList.value = (await getPublicityGrogrammes())?.list;
  // 新消息通知
  messageList.value = (await getMessageList())?.list;

  // 获取已经被read的信息
  const hasShowedMessageListStr = localStorage.getItem(localMessageStatusKey);
  if (hasShowedMessageListStr) {
    hasShowedMessageList.value = JSON.parse(hasShowedMessageListStr);
  }
  // 健康城市达成率
  healthStatistics.value = await getCityHealthStatistics(
    userRegions.isNationwide,
    destSelectRef.value.userSelectedRegions.provinceId,
    destSelectRef.value.userSelectedRegions.cityId,
    destSelectRef.value.userSelectedRegions.areaId
  );
  // console.log("healthStatistics:", healthStatistics);
  healthEducationStrObj.value = healthStatistics.value.healthEducation;
  useDrugStrObj.value = healthStatistics.value.illnessInsurance;
  diseaseProtectStrObj.value = healthStatistics.value.medicationManagement;
  // 当日数据看板
  dayStatistics.value = await getDayStatistics(
    userRegions.isNationwide,
    destSelectRef.value.userSelectedRegions.provinceId,
    destSelectRef.value.userSelectedRegions.cityId,
    destSelectRef.value.userSelectedRegions.areaId
  );
  // 返回数据明细
  await getCurDayStaticData();
  setEchart();
}

onMounted(async () => {
  const userStore = useUserStoreHook();
  userInfo.value = userStore.userInfo;
  console.log("userInfo.value:", userInfo.value);
  // 获取详情数据必须放到chart后
  setUpdateStr();
  initChart();
  // 宣传方案
  initDataAndChart();

  window.addEventListener("resize", resizeChart);
});
onUnmounted(() => {
  window.removeEventListener("resize", resizeChart);
});
</script>
<style scoped lang="scss">
.section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.part {
  width: 32.5%;
  flex-shrink: 0;
  height: 290px;

  .p-title {
    .more {
      color: #666;
      cursor: pointer;
      display: flex;
      font-size: 14px;
      font-weight: 400;
      align-items: center;
      height: 14px;
      line-height: 14px;

      a {
        display: inline-flex;
        align-items: center;
      }
    }
  }

  .p-cont {
    margin-top: 20px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;

    .info {
      max-width: calc(100% - 140px);
      width: 100%;

      .info-title {
        font-size: 16px;
        word-break: keep-all;
        white-space: nowrap;
        width: 97%;
        overflow: hidden;
        text-overflow: ellipsis;
        color: #333;
        font-weight: 400;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .info-t-txt {
        display: inline-block;
        width: calc(100% - 50px);
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .info-icon {
        margin-left: 10px;
        background: rgba(246, 97, 117, 1);
        padding: 2px 5px;
        border-radius: 2px;
        font-weight: bold;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.7);
        text-align: center;
        display: inline-block;
        box-sizing: border-box;
      }

      .info-tip {
        font-size: 14px;
        color: #666;
        margin-top: 6px;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: keep-all;
        white-space: nowrap;
      }
    }

    .time {
      min-width: 120px;
      word-break: keep-all;
      white-space: nowrap;
      color: #666;
      font-size: 14px;
    }
  }

  &.part-nopadding {
    padding: 0px;
    background: none;
  }

  .self-info {
    display: flex;
    align-items: center;
    height: 70px;
    background-color: rgba(69, 147, 244, 1);
    padding: 20px;
    // box-sizing: border-box;
    border-radius: 4px;

    .face {
      width: 50px;
      height: 50px;
      border-radius: 50px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .s-des {
      color: white;
      margin-left: 20px;

      .s-des-name {
        font-size: 16px;
        font-weight: 400;
        color: #ffffff;
      }

      .s-des-job {
        font-size: 12px;
        font-weight: 400;
        color: #ffffff;
      }
    }
  }

  .short-entry {
    margin-top: 10px;
    padding: 20px;
    height: 210px;
    background-color: white;
    color: rgba(51, 51, 51, 1);
    border-radius: 4px;

    .cont {
      height: 120px;
      margin-top: 10px;
      display: grid;
      grid-template-columns: repeat(2, 120px);
      grid-template-rows: repeat(2, 40px);
      align-content: space-evenly;
      justify-content: space-evenly;
      justify-items: baseline;

      .el-button {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.panel {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0px;
  }

  .panel-title-cont {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .title {
    font-size: 18px;
    font-weight: 500;
    color: #333333;
    display: flex;
    align-items: center;

    svg {
      margin: 0px 5px;
    }
  }

  .time {
    font-size: 14px;
    font-weight: bold;
    color: #bbb;
    margin-left: 10px;
  }

  .pie {
    // 饼图
    width: 100%;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // margin-top: 20px;
    .p-item {
      width: 30%;
      height: inherit;
      display: flex;
      align-items: center;
      position: relative;
      flex-direction: column;
      padding-top: 10px;
      justify-content: center;

      .p-title {
        font-size: 18px;
        font-weight: 500;
        color: #222222;
      }

      .pie-cont {
        margin-top: 10px;
        position: relative;
        width: 200px;
        height: 200px;

        .pie-chart {
          width: inherit;
          height: inherit;
          position: relative;
        }

        .pie-detail {
          width: 160px;
          height: 160px;
          border-radius: 120px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          text-align: center;
          box-sizing: border-box;
          padding-top: 25px;

          &.pink {
            background-color: #fff6f6;
          }

          &.yellow {
            background-color: #ebf6f6;
          }

          &.green-in {
            background-color: #eff5ff;
          }

          .info {
            width: 100%;
            text-align: center;
            margin: auto;
            margin-bottom: 3px;
            font-size: 14px;
            color: #222;

            .label {
              color: #666;
              margin-right: 5px;
            }

            &.bold {
              font-weight: bold;
              margin-top: 10px;
            }
          }

          .num {
            color: red;
            font-size: 30px;
          }
        }
      }
    }
  }

  .board {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(4, auto);
    grid-template-rows: repeat(2, 120px);
    grid-gap: 10px;
    align-content: space-between;

    .b-item {
      border-radius: 4px;
      border: 1px solid #eee;
      padding: 20px;
      user-select: none;
      position: relative;

      &.active {
        background: #4993fa;
        color: white;

        .b-title {
          color: white;
        }

        .b-compare {
          .b-c-item {
            color: white;

            svg {
              background: white;
              // fill: rgba(255, 255, 255, 1);
            }
          }
        }
      }

      .b-title {
        color: #333;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
      }

      .b-num {
        font-size: 36px;
        font-weight: bold;
      }

      .b-compare {
        margin-top: 10px;

        .b-c-item {
          margin-top: 10px;
          display: flex;
          align-items: center;
          color: #333;
          font-size: 14px;

          svg {
            padding: 2px;
            width: 16px;
            height: 16px;
            border-radius: 14px;
            margin: 0px 2px;
            // fill: rgba(255, 255, 255, 0.6);
          }
        }
      }

      .b-item-tip {
        background: rgba(48, 49, 51, 1);
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
        height: 32px;
        font-size: 12px;
        line-height: 32px;
        box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
        z-index: 100;
        padding: 0px 10px;
        border-radius: 4px;
      }
    }
  }

  .line {
    margin-top: 40px;
    width: 100%;
    height: 400px;
  }
}

.dialog-detail {
  width: 100%;

  .dialog-item {
    margin-top: 20px;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;

    width: 100%;

    .label {
      width: 60px;
      font-weight: bold;
      color: #333;
    }

    .content {
      width: calc(100% - 60px);

      pre {
        width: 100%;
        white-space: break-spaces;
        line-height: 2;
      }

      .con-item {
        margin-bottom: 10px;

        .down-href {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
